package org.example.service.impl;

import io.seata.rm.tcc.api.BusinessActionContext;
import org.example.dao.StudentDAO;
import org.example.pojo.Student;
import org.example.service.IStudentTccAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class StudentTccAction implements IStudentTccAction {
    private static final Logger logger = LoggerFactory.getLogger(StudentTccAction.class);
    @Autowired
    private StudentDAO studentDAO;

    @Override
    @Transactional
    public boolean prepare(BusinessActionContext businessActionContext, int id, int changescore) {
        logger.info("student--try--开启");
        Student student = studentDAO.findOne(id);
        if(student == null){
            student = new Student();
            student.setId(id);
            student.setScore(changescore);
            student.setChangescore(0);
            studentDAO.save(student);
        }else{
            //判断该记录是否被别的事务占用
            if(student.getChangescore() > 0){
                logger.info("student--try--资源被占");
                return false;
            }
            //冻结资源
            int newScore = student.getScore() + changescore;
            student.setScore(newScore);
            student.setChangescore(changescore);
            studentDAO.save(student);
        }
        logger.info("student--try--提交");
        return true;
    }

    @Override
    @Transactional
    public boolean commit(BusinessActionContext businessActionContext) {
        logger.info("student--confirm--开启");
        int id = (int) businessActionContext.getActionContext("studentId");
        Student student = studentDAO.findOne(id);
        student.setChangescore(0);
        studentDAO.save(student);
        logger.info("student--confirm--结束");
        return true;
    }

    @Override
    @Transactional
    public boolean rollback(BusinessActionContext businessActionContext) {
        logger.info("student--cancel--开启");
        int id = (int) businessActionContext.getActionContext("studentId");
        Student student = studentDAO.findOne(id);
        //释放资源
        if(student != null){
            int newScore = student.getScore() - student.getChangescore();
            student.setScore(newScore);
            student.setChangescore(0);
            studentDAO.save(student);
        }
        logger.info("student--cancel--结束");
        return true;
    }
}
